from django.shortcuts import render

# Create your views here.
# 面包学导航
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import ListAPIView, GenericAPIView, CreateAPIView
from goods.models import GoodsCategory, SKU
from goods.serializers import SKUSSerialziers, SKUIndexSerializer,  SKUHistorySerialzier
from goods.utils import PageNum
from drf_haystack.viewsets import HaystackViewSet
from django_redis import get_redis_connection


class CategoriesView(APIView):
    """
        面包屑导航分类数据获取
    """

    def get(self, request, pk):
        # 1、获取三级分类id
        # 2、查询三级分类对象
        cat3 = GoodsCategory.objects.get(id=pk)
        # 3、通过三级分类查询二级分类
        cat2 = cat3.parent
        # 4、通过二级分类查询依级分类
        cat1 = cat2.parent
        # 5、返回结果
        return Response({
            'cat1': cat1.name,
            'cat2': cat2.name,
            'cat3': cat3.name,
        })


class SKUSView(ListAPIView):
    serializer_class = SKUSSerialziers
    # 分页
    pagination_class = PageNum
    # 过滤排序
    filter_backends = [OrderingFilter]  # 过滤排序
    ordering_fields = ('create_time', 'sales', 'price')

    def get_queryset(self):
        # 获取前端传递路径中匹配pk值
        pk = self.kwargs['pk']
        return SKU.objects.filter(category_id=pk)


class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer


class SKUHistoryView(CreateAPIView, ListAPIView):
    # 用户浏览记录

    def get_queryset(self):
        #     获取当前用户对象
        user = self.request.user
        # 根据当前对象获取浏览对象
        #     查询redis数据库
        conn = get_redis_connection('history')
        sku_ids = conn.lrange('history_%s' % user.id, 0, 100)
        skus = SKU.objects.filter(id__in= sku_ids)
        return skus

    def get_serializer_class(self):
        # 不同请求反活力不同序列化器
        if self.request.method == "POST":
            return SKUHistorySerialzier
        else:
            return SKUSSerialziers